/// <reference path="../utilities/FXDom.js" />
/// <reference path="../utilities/Markup.js" />
/// <reference path="../utilities/Xpcom.js" />
///--------------------------------------------------------------------
/// <file name="NAMFoxToolbar.js">
///   Provides logic for the NAMFox toolbar.
/// </file>
///--------------------------------------------------------------------

with (NAMFox) {

var NAMFoxToolbar = {
    _getTextArea: function() {
        /// <summary>
        /// Gets a text area to which to add text or markup.
        /// </summary>
        /// <returns type="TextArea" />

        var textArea = document.commandDispatcher.focusedElement;

        if (!textArea || textArea.clientWidth === 0) {
            textArea = content.document.__namfox__.textArea;
        }

        if (!textArea) {
            alert("There is no text area to add text to.");
            return null;
        }

        return textArea;
    },

    addCustomMessage: function(messageKey) {
        /// <summary>
        ///   Adds a custom message to a text area on the page.
        /// </summary>
        /// <param name="messageKey" type="String">
        ///   The key of the message to add.
        /// </param>

        var textArea = this._getTextArea();

        if (textArea) {
            Markup.addCustomMessage(messageKey, textArea);
        }
    },

    addText: function(text) {
        /// <summary>
        ///   Adds markup or text to a text area on the page.
        /// </summary>
        /// <param name="text" type="String">
        ///   The text to add.
        /// </param>

        var textArea = this._getTextArea();

        if (textArea) {
            Markup.addText(text, textArea, SelectionRule.MoveCursorToClose);
        }
    },

    loadUrl: function(event, url) {
        /// <summary>Loads a URL from the toolbar.</summary>
        /// <param name="event">
        ///   The MouseEvent created by a toolbar button click.
        /// </param>
        /// <param name="url">
        ///   The URL to load.
        /// </param>

        var target = whereToOpenLink(event);
        
        if (target === "current" && $.getConfig().toolbar.linkBehavior === LinkBehavior.AlwaysOpenInNewTab) {
            target = "tab";
        }
        
        openUILinkIn(url, target);
    },

    onLoad: function() {
        /// <summary>
        /// Ensures all menu items can use middle click to open links in new tabs.
        /// </summary>

        var handler = function() {
            if ($.startsWith(this.id, "namfox-")) {
                $FX(this).find("menuitem").each(
                    function() {
                        if (this.getAttribute("oncommand")) {
                            this.addEventListener(
                                "click",
                                function(event) {
                                    checkForMiddleClick(this, event);
                                },
                                false);
                        }
                    }
                );

                if (this.getAttribute("oncommand")) {
                    this.addEventListener(
                        "click",
                        function(event) {
                            checkForMiddleClick(this, event);
                        },
                        false);
                }
            }
        }

        // Get all the toolbar buttons currently visible
        $FX("toolbarbutton", document).each(handler);

        // And all the ones still in the toolbarpalette.
        $FX(document.getElementById("navigator-toolbox").palette).find("toolbarbutton").each(handler);
    },

    refreshCustomMessages: function() {
        /// <summary>
        ///   Refreshes the list of custom messages that users can place
        ///   into a text area.
        /// </summary>

        var messageList = $FX("#namfox-custom-messages-popup").get(0);
        var referenceElement = messageList.firstChild;

        while (referenceElement.nodeName !== "menuseparator") {
            messageList.removeChild(referenceElement);
            referenceElement = messageList.firstChild;
        }

        $.messages.enumerate(
            function(message) {
                var menuItem = document.createElement("menuitem");
                menuItem.setAttribute("label", message.name);
                menuItem.setAttribute("value", message.key);
                menuItem.addEventListener(
                    "command",
                    function() {
                        NAMFoxToolbar.addCustomMessage(message.key);
                    },
                    false);

                messageList.insertBefore(menuItem, referenceElement);
            }
        );

        var defaultMessage = document.createElement("menuitem");
        defaultMessage.setAttribute("label", "Default Message");
        defaultMessage.setAttribute("value", "defaultMessage");
        defaultMessage.addEventListener(
            "command",
            function() {
                NAMFoxToolbar.addCustomMessage('defaultMessage');
            },
            false);

        messageList.insertBefore(defaultMessage, referenceElement);
    },

    refreshPersonalUrls: function() {
        /// <summary>
        ///   Refreshes the list of personal URLs (blog and gallery) for users
        ///   to click.
        /// </summary>

        var userName = $.getCurrentUser().userName;
        if (!userName) {
            $FX("#namfox-my-blog").attr("className", "hidden");
            $FX("#namfox-my-gallery").attr("className", "hidden");
            $FX("#namfox-my-post-history").attr("className", "hidden");
            $FX("#namfox-crs-profile-overview").attr("className", "hidden");
            $FX("#namfox-crs-latest-contributions").attr("className", "hidden");
            $FX("#namfox-crs-queue").attr("className", "hidden");
        }
        else {
            var blog = $FX("#namfox-my-blog").attr("className", "").get(0);
            var gallery = $FX("#namfox-my-gallery").attr("className", "").get(0);
            var crsProfileOverview = $FX("#namfox-crs-profile-overview").attr("className", "").get(0);
            var crsLatestContributions = $FX("#namfox-crs-latest-contributions").attr("className", "").get(0);
            var crsQueue = $FX("#namfox-crs-queue").attr("className", "").get(0);
            $FX("#namfox-my-post-history").attr("className", "");

            blog.addEventListener(
                "command",
                function(event) {
                    NAMFoxToolbar.loadUrl(event, "http://blogs.neoseeker.com/" + userName + "/");
                },
                false);
            gallery.addEventListener(
                "command",
                function(event) {
                    NAMFoxToolbar.loadUrl(event, "http://gallery.neoseeker.com/" + userName + "/");
                },
                false);
            crsProfileOverview.addEventListener(
                "command",
                function(event) {
                    NAMFoxToolbar.loadUrl(event, "http://crs.neoseeker.com/member/" + userName + "/");
                },
                false);
            crsLatestContributions.addEventListener(
                "command",
                function(event) {
                    NAMFoxToolbar.loadUrl(event, "http://crs.neoseeker.com/member/" + userName + "/latest/");
                },
                false);
            crsQueue.addEventListener(
                "command",
                function(event) {
                    NAMFoxToolbar.loadUrl(event, "http://crs.neoseeker.com/member/" + userName + "/queue/");
                },
                false);
        }
    },

    refreshSaveCustomMessages: function() {
        /// <summary>
        ///   Refreshes the list of custom messages that users can use
        ///   to save or overwrite custom messages.
        /// </summary>

        var messageList = $FX("#namfox-save-custom-message-list").get(0);
        var referenceElement = messageList.firstChild;

        while (referenceElement) {
            messageList.removeChild(referenceElement);
            referenceElement = messageList.firstChild;
        }

        $.messages.enumerate(
            function(message) {
                var menuItem = document.createElement("menuitem");
                menuItem.setAttribute("label", "Save over " + message.name);
                menuItem.setAttribute("value", message.key);
                menuItem.addEventListener(
                    "command",
                    function() {
                        NAMFoxToolbar.saveCustomMessage(message.key);
                    },
                    false);

                messageList.appendChild(menuItem);
            }
        );

        var defaultMessage = document.createElement("menuitem");
        defaultMessage.setAttribute("label", "Default Message");
        defaultMessage.setAttribute("value", "defaultMessage");
        defaultMessage.addEventListener(
            "command",
            function() {
                NAMFoxToolbar.saveCustomMessage('defaultMessage');
            },
            false);

        messageList.appendChild(defaultMessage);
    },

    refreshSmileys: function() {
        /// <summary>
        ///   Refreshes the list of smileys that users can choose from
        ///   based on their preferences.
        /// </summary>

        var check = new BigInteger($.getConfig().toolbar.enabledSmileys);

        var smileyCount = 92;
        for (var i = 0; i < smileyCount; ++i) {
            var menuItem = $FX("#namfox-smileys-popup menuitem[data-index=" + i + "]").get(0);

            if (check.bitwiseAnd(BigInteger.fromMultipleOfTwo(i)).notEquals(0)) {
                menuItem.className = "menuitem-iconic";
            }
            else {
                menuItem.className = "hidden";
            }
        }
        
        var count = {};
        var customSmileyUrls = $.getCurrentUser().getCustomSmileyUrls(count);

        function createCallback(url) {
            return function() {
                NAMFoxToolbar.addText('[img]' + url + '[/img]');
            };
        }

        for (var i = 0; i < 5; ++i) {
            var listItem = $FX("#namfox-custom-smiley-" + (i + 1).toString());
            if (i >= count.value) {
                listItem.attr("className", "hidden");
                continue;
            }

            var url = customSmileyUrls[i];
            listItem
                .attr("image", url)
                .command(
                    createCallback(url),
                    true);
        }
    },

    saveCustomMessage: function(messageKey) {
        /// <summary>
        ///   Overwrites a custom message according to data
        ///   in the subject and body area of a post.
        /// </summary>
        /// <param name="messageKey" type="String">
        ///   The key of the message to overwrite.
        /// </param>

        var subjectArea = $FX("#subject", content.document);
        var bodyArea = $FX("#post_textarea", content.document);

        if (subjectArea && bodyArea) {
            if (messageKey === "defaultMessage") {
                var message = $.messages.getDefaultMessage();
                message.text = bodyArea.val();
            }
            else {
                var message = $.messages.getMessage(messageKey);
                message.name = subjectArea.val();
                message.text = bodyArea.val();
            }
        }
        else {
            alert("You must be on the post reply page in order to save a custom message!");
        }

        $.messages.save();
    },

    searchFiles: function(event, fileType) {
        /// <summary>
        ///   Searches Neoseeker for files of a given type.
        /// </summary>
        /// <param name="fileType" type="String">
        ///   The type of files to search for.
        /// </param>

        var searchText = $.trim(document.getElementById("namfox-search-neofiles-text").value);
        this.loadUrl(
            event,
            "http://files.neoseeker.com/search.php?keywords=" +
            $.urlEncode(searchText) +
            "&searchGroup=" +
            fileType
        );
    },

    searchMembers: function(event) {
        /// <summary>
        ///   Searches Neoseeker for data from a given category.
        /// </summary>
        /// <param name="memberName" type="String">
        ///   The name of the member to search for.
        /// </param>

        var memberName = $.trim(document.getElementById("namfox-search-neoseeker-text").value);
        this.loadUrl(
            event,
            "http://www.neoseeker.com/members/directory.html?keywords=" +
            $.urlEncode(memberName)
        );
    },

    searchNeoseeker: function(event, category) {
        /// <summary>
        ///   Searches Neoseeker for data from a given category.
        /// </summary>
        /// <param name="category" type="String">
        ///   The type of data to search for.
        /// </param>

        var searchText = $.trim(document.getElementById("namfox-search-neoseeker-text").value);
        this.loadUrl(
            event,
            "http://www.neoseeker.com/seeker.php?keywords=" +
            $.urlEncode(searchText) +
            "&searchGroup=" +
            category
        );
    },

    showAbout: function() {
        /// <summary>Shows the about dialog.</summary>

        window.openDialog(
            "chrome://namfox/content/about.xul",
            "About NAMFox",
            "modal,centerscreen,chrome"
        );
    },

    showDonatePage: function(event) {
        /// <summary>
        /// Loads the PayPal donation page.
        /// </summary>

        // Either a middle click or the user has opted to always
        // show links in a new tab.
        var useNewTab = event.button === 1 ||
            $.getConfig().toolbar.linkBehavior === LinkBehavior.AlwaysOpenInNewTab;

        if (useNewTab) {
            gBrowser.selectedTab = gBrowser.addTab("");
        }

        var form = "";
        form += '<form style="display: none;" id="namfox-paypal-form" action="https://www.paypal.com/cgi-bin/webscr" method="post">';
        form += '<input type="hidden" name="cmd" value="_s-xclick">';
        form += '<input type="hidden" name="encrypted" value="-----BEGIN PKCS7-----MIIHLwYJKoZIhvcNAQcEoIIHIDCCBxwCAQExggEwMIIBLAIBADCBlDCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UEAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBhbC5jb20CAQAwDQYJKoZIhvcNAQ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13qt2A64Pgi8U1q8w/7zaG0mKXIsBoY5Aw9XDQzNV4KoA2urDi+ZKA==-----END PKCS7-----">';
        form += '<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">';
        form += '<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">';
        form += '</form>';

        $FX("body", content.document).append(form);
        $FX("#namfox-paypal-form", content.document).get(0).submit();
    },

    showPreferences: function() {
        /// <summary>Shows the preferences dialog.</summary>

        window.openDialog(
            "chrome://namfox/content/preferences/preferences.xul",
            "NAMFox Preferences",
            "centerscreen,chrome,toolbar,minimizable=yes"
        );
    }
};

};

window.addEventListener("load", NAMFoxToolbar.onLoad, false);